package com.heima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.Result;
import com.heima.domain.dto.PageDTO;
import com.heima.domain.po.Drugs;
import com.heima.domain.query.DrugsQuery;
import com.heima.mapper.DrugsMapper;
import com.heima.service.IDrugsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 药物信息表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-08-04
 */
@Service
public class DrugsServiceImpl extends ServiceImpl<DrugsMapper, Drugs> implements IDrugsService {
    public Result findByPage(DrugsQuery drugsQuery){
        String name = drugsQuery.getName();
        Integer category = drugsQuery.getCategory();
        Integer pageNum = drugsQuery.getPageNum();
        Integer pageSize = drugsQuery.getPageSize();
        Page<Drugs> p = this.lambdaQuery()
                .like(StringUtils.isNotBlank(name), Drugs::getName, name)
                .eq(category != null, Drugs::getCategory, category)
                .orderByDesc(Drugs::getUpdateTime)
                .page(new Page<>(pageNum, pageSize));
        List<Drugs> records = p.getRecords();
        if (records.isEmpty()) { // 如果结果为空
            return Result
                    .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageNum, new ArrayList<>())); // 返回空数据的分页结果
        }
        return Result
                .success(new PageDTO<>(p.getTotal(), p.getSize(), p.getPages(), (long)pageSize, records)); // 返回查询到的数据分页结果
    }
}
